package pl.javarsovia.javarsovia4android.util;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

/**
 * @author mgrzechocinski
 * @since 2010-06-12
 */
public class XMLUtils {
	private static DocumentBuilderFactory documentBuilderFactory;

	static {
		documentBuilderFactory = DocumentBuilderFactory.newInstance();
		documentBuilderFactory.setIgnoringComments(true);
	}

	public static Element getRoot(InputStream inputStream) {
		try {
			return doGetRoot(inputStream);
		} catch (Exception ex) {
			throw new RuntimeException("Exception during getting root element", ex);
		}
	}

	private static Element doGetRoot(InputStream inputStream) throws Exception {
		DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
		Document dom = builder.parse(inputStream);
		return removeWhitespaceNodes(dom.getDocumentElement());
	}

	public static Element removeWhitespaceNodes(Element e) {
		NodeList children = e.getChildNodes();
		for (int i = children.getLength() - 1; i >= 0; i--) {
			Node child = children.item(i);
			if (child instanceof Text && isEmpty(child)) {
				e.removeChild(child);
			} else if (child instanceof Element) {
				removeWhitespaceNodes((Element) child);
			}
		}
		return e;
	}

	private static boolean isEmpty(Node child) {
		return ((Text) child).getData().trim().length() == 0;
	}

	public static String getStringAttribute(Node node, String attributeName) {
		return node.getAttributes().getNamedItem(attributeName).getNodeValue();
	}
}
